package com.siqi.hr.common.generator;

import org.apache.commons.lang.ArrayUtils;

/**
 * 唯一id生成器辅助类(xiaogq)
 */
public class CharTransformer {
	public static final char[] chars = new String("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz").toCharArray();
	public static final int magnifi = 62;

	public static int toInt(char a) {
		int temp = a;
		if ((temp > 47) && (temp < 58))
			temp -= 48;
		else if ((temp >= 65) && (temp <= 90))
			temp -= 55;
		else if ((temp >= 97) && (temp <= 122))
			temp -= 61;
		else {
			temp = 0;
		}
		return temp;
	}

	public static char encodeCount(int count) {
		if ((count > 61) || (count < 0))
			throw new IllegalArgumentException(count + "参数不在0-61范围内");
		return chars[count];
	}

	public static int median(int source, int man) {
		if (source / man <= 0) {
			return 1;
		}
		return median(source / man, man) + 1;
	}

	public static int magnification(int man, int bit) {
		if (bit > 1) {
			return magnification(man, --bit) * man;
		}
		return 1;
	}

	public static char[] encode(int source) {
		int bit = median(source, 62);

		char[] result = new char[bit];
		for (int i = bit; i > 0; i--) {
			if (i == 1) {
				result[0] = encodeCount(source);
			} else {
				int divisor = source / magnification(62, i);
				result[(i - 1)] = encodeCount(divisor);
				source %= magnification(62, i);
			}
		}
		ArrayUtils.reverse(result);
		return result;
	}

	public static int encodeCount(String source) {
		char[] s = source.toCharArray();
		ArrayUtils.reverse(s);
		int result = 0;

		for (int i = 0; i < s.length; i++) {
			int temp = i + 1;
			result += toInt(s[i]) * magnification(62, temp);
		}

		return result;
	}
	
	public static void main(String[] args) {
		for (char c : chars) {
			System.out.println(String.valueOf(c) + toInt(c));
		}

		for (int i = 0; i < 62; i++) {
			System.out.print(i + " : " + encodeCount(i) + "//");
		}

		System.out.println(encodeCount("0rdsx"));
		System.out.println(encodeCount("rdsx"));
		System.out.println(encode(9999999));
		System.out.println(encode(999999));
		System.out.println(median(342459, 62));
	}
}